usage(){
  echo "Useage: $0 [PRJ_PATH] [gen cscope db] [pattern file]"
}

appendPattern(){
  TEMP=$1
  echo "${TEMP}"
  if [ "${FILE_PATTERN}" = "" ];
  then
    FILE_PATTERN=${FILE_PATTERN}' -name '$TEMP
  else
    FILE_PATTERN=${FILE_PATTERN}' -or -name '$TEMP
  fi
}

if [ $# -lt 1 ];
then
  usage
  exit
fi

CODE_PATH=$1
GEN_DB=$2
PATTERN_FILE=$3

if ! [ -d ${CODE_PATH} ];
then
  echo "${CODE_PATH} is not exist"
  exit
fi


if [ "${PATTERN_FILE}" = "" ];
then
  PATTERN_FILE=".cscope_filter"
fi

echo "remove all cscope files"
cd "${CODE_PATH}"
CODE_PATH=$(pwd)
echo $CODE_PATH
rm cscope.* ncscope.*

echo "generate cscope.files"

FILE_PATTERN=""

export FILE_PATTERN

egrep -v "^#" ${PATTERN_FILE} > pattern.txt

while read line
do
appendPattern "${line}"
done<pattern.txt

#for line in $(cat pattern.txt)
#do
#  if [ "${line}" != "" ];
#  then
#	echo "${line}"
    #appendPattern ${line}
#  fi
#done



echo "-------------------------------------------"
echo ${FILE_PATTERN}
tmp=`echo ${FILE_PATTERN}`
echo "${CODE_PATH}"
find ${CODE_PATH} -type f `echo ${FILE_PATTERN}` | grep -v " " > ${CODE_PATH}/cscope_temp.files

while read line
do
  if [ -e ${line} ];
  then
    if ! [ -h ${line} ];
    then
      echo ${line} >> ${CODE_PATH}/cscope.files
    else
      #we can ignore the link because the file which this softr link point to must have been included
      echo "file "${line}" is a soft link"
    fi
  else
    echo "file "${line}" is not exist"
  fi
done<${CODE_PATH}/cscope_temp.files

rm pattern.txt

echo "create cscope index"

if [ "${GEN_DB}" = "" ] || [ "${GEN_DB}" = "yes" ] || [ "${GEN_DB}" = "y" ] || [ "${GEN_DB}"="YES" ] || [ "${GEN_DB}"="Y" ];
then
  cscope -Rbkq -i cscope.files
fi

echo "finish!!!"
